package info.wegosoft.android.activity;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import info.wegosoft.R;
import info.wegosoft.android.model.MBlog;
import info.wegosoft.android.model.Platform;
import info.wegosoft.android.qauth.sina.OAuthConstant;
import info.wegosoft.android.qauth.sina.Weibo;
import info.wegosoft.android.qauth.sina.WeiboException;
import info.wegosoft.android.qauth.tencent.OAuth;
import info.wegosoft.android.qauth.tencent.QWeiboSyncApi;
import info.wegosoft.android.qauth.tencent.QWeiboType.ResultType;
import info.wegosoft.android.util.TimeUtil;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

/**  
 * Filename:    DetailMBlogActivity.java 
 * Package:     info.wegosoft.android.activity 
 * Description: TODO(这里用一句话描述这个类的作用)
 * Copyright:   Copyright (c) wegosoft.info 2011  
 * @author:     李辉 
 * email:       fzlihui@gmail.com
 * @version:    1.0  
 * Create at:   2011-6-13 下午11:22:19  
 */
public class DetailMBlogActivity extends Activity{
	
	private MBlog mBlog = null;
	private int platformType;
	private String addCacheFlag = "";
	private ImageView userFace;
	private ImageView mblogImage;
	private Bitmap faceBitmap = null;	
	private Bitmap microBlogImageBitmap = null;
	private Button tweet_redirect;
	private Button tweet_comment;
	private UIHandler handler;
	private String repostNum;
	private String commentNum;
	private String imageURL;
	//如果状态图片是原微博的则为true
	private boolean isSourceImage = false;
	private static final String BMIDDLE_IMAGES_CACHE_DIR = "bmiddle";
	
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.detail_mblog);
		
		setTitle("微博");
	
		handler = new UIHandler();
		
		mBlog = (MBlog) getIntent().getSerializableExtra("mblog");
		
		platformType = this.getSharedPreferences("platform",Context.MODE_PRIVATE).getInt("type", -1);
		
		switch (platformType) {
			case Platform.SINA_PLATFORM:
				addCacheFlag = "sina";
				break;
			case Platform.TENCENT_PLATFORM:
				addCacheFlag = "tencent";
				break;
			default:
				break;
		}
		
		this.initContent();
	}	
	
	/**
	 * 初始化界面内容
	 */
	private void initContent(){
		//微博内容
		TextView textView = (TextView) findViewById(R.id.tweet_message);
		
		textView.setText(mBlog.getText());
		
		//用户名
		TextView userName = (TextView) findViewById(R.id.tweet_profile_name);
		
		userName.setText(mBlog.getScreen_name());
		
		//微博发布来源
		TextView fromTextView = (TextView) findViewById(R.id.tweet_via);
		
		fromTextView.setText(Html.fromHtml("来自：" + mBlog.getFrom()));
		
		//发布时间
		TextView time = (TextView) findViewById(R.id.tweet_updated);
		
		time.setText(TimeUtil.formatDateToString(mBlog.getCreated_at()));
		
		//用户头像
		userFace = (ImageView) findViewById(R.id.tweet_profile_preview);
		
		//此条微博包含的图片
		if(mBlog.getBmiddle_pic()!=null && !mBlog.getBmiddle_pic().trim().equals("")){
			
			imageURL = mBlog.getOriginal_pic().trim();
			
			mblogImage = (ImageView) findViewById(R.id.tweet_upload_pic);
			
			mblogImage.setVisibility(View.VISIBLE);
			
		}
		
		MBlog sourceMblog = mBlog.getSourceMBlog();
		
		if(sourceMblog != null){
			LinearLayout sourceLinearLayout = (LinearLayout) findViewById(R.id.src_text_block);
			
			sourceLinearLayout.setVisibility(View.VISIBLE);
			
			TextView sourceText = (TextView) findViewById(R.id.tweet_oriTxt);
			
			sourceText.setText(Html.fromHtml("@" + sourceMblog.getName() + "：" + sourceMblog.getText()));
			
			//原微博包含的图片
			if(sourceMblog.getBmiddle_pic()!=null && !sourceMblog.getBmiddle_pic().trim().equals("")){
				
				isSourceImage = true;
				
				imageURL = sourceMblog.getOriginal_pic().trim();
				
				mblogImage = (ImageView) findViewById(R.id.tweet_upload_pic2);
				
				mblogImage.setVisibility(View.VISIBLE);
			}
		}
		
		if(mblogImage!=null){
			
			mblogImage.setOnClickListener(new OnClickListener() {
				
				public void onClick(View v) {
					
					Intent intent = new Intent();
					
					Bundle bundle = new Bundle();
					
					bundle.putString("imageURL", imageURL);
					
					bundle.putBoolean("isSourceImage", isSourceImage);
					
					bundle.putSerializable("mblog", mBlog);
					
					intent.putExtras(bundle);
					
					intent.setClass(DetailMBlogActivity.this, ImageViewActivity.class);
					
					startActivity(intent);
				}
			});
			
		}
		//下部评论TextView，当按钮使用
		TextView tvComment = (TextView) findViewById(R.id.tvComment);
		
		tvComment.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {

				Intent intent = new Intent();
				
				Bundle bundle = new Bundle();
				
				bundle.putSerializable("mblog", mBlog);
				
				intent.putExtras(bundle);
				
				intent.setClass(DetailMBlogActivity.this, CommentMBlogActivity.class);
				
				startActivity(intent);
				
			}
		});
		
		//下部转发TextView，当按钮使用
		TextView tvForward = (TextView) findViewById(R.id.tvForward);
		
		tvForward.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {

				Intent intent = new Intent();
				
				Bundle bundle = new Bundle();
				
				bundle.putSerializable("mblog", mBlog);
				
				intent.putExtras(bundle);
				
				intent.setClass(DetailMBlogActivity.this, RepostMBlogActivity.class);
				
				startActivity(intent);
				
			}
		});
		
		//转发按钮，按钮上显示转发数
		tweet_redirect = (Button) findViewById(R.id.tweet_redirect);
		
		//评论按钮，按钮上显示评论数
		tweet_comment = (Button) findViewById(R.id.tweet_comment);
		
		tweet_comment.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				
				//跳转到评论列表
				Intent intent = new Intent();
				
				Bundle bundle = new Bundle();
				
				bundle.putSerializable("mblog", mBlog);
				
				intent.putExtras(bundle);
				
				intent.setClass(DetailMBlogActivity.this, CommentListActivity.class);
				
				startActivity(intent);
	
			}
			
		});
		
		new UpdateImageThread().start();
		
		//获取转发和评论数
		new Thread(){

			public void run() {
				
				String result;
				
				int platformType = DetailMBlogActivity.this.getSharedPreferences("platform",Context.MODE_PRIVATE).getInt("type", -1);
				
				try {
					switch (platformType) {
					
						case Platform.SINA_PLATFORM:
							
							 Weibo weibo = OAuthConstant.getInstance().getWeibo();	
							 
							 result = weibo.getCountsJSONStringByID(mBlog.getId());
							 
							 JSONArray jsonArray = new JSONArray(result);
							 
							 if(jsonArray.length()==1){
								 
								 JSONObject jsonObject = jsonArray.getJSONObject(0);
								 
								 repostNum = jsonObject.getString("rt");
								 
								 commentNum = jsonObject.getString("comments");
								 
								 handler.sendEmptyMessage(UPDATE_COUNT);
							 }
							 
							 break;
							 
						case Platform.TENCENT_PLATFORM:
							
							 QWeiboSyncApi api = new QWeiboSyncApi();
							 
							 SharedPreferences preference = getSharedPreferences("tencent_qauth",Context.MODE_PRIVATE);
							 
							 result = api.getCountByID(OAuth.AppKey, OAuth.AppSecret, preference.getString("AccessToken", null),preference.getString("AccessTokenSecret", null), ResultType.ResultType_Json, mBlog.getId());
							 
							 JSONObject jsonObject = new JSONObject(result);
							 
							 if(!jsonObject.isNull("data")){
								 
								 JSONObject count = jsonObject.getJSONObject("data").getJSONObject(mBlog.getId());
									
								 repostNum = count.getString("count");
								 
								 commentNum = count.getString("mcount");
								 
								 handler.sendEmptyMessage(UPDATE_COUNT);
							 }
							 
							 break;
						default:
							 break;
					}
				} catch (WeiboException e) {
			
					e.printStackTrace();
					
				} catch (JSONException e) {
					
					e.printStackTrace();
					
				}
			}
	
		}.start();		
	}
	
	private static final int UPDATE_FACE = 0;
	private static final int UPDATE_IMAGE = 1;
	private static final int UPDATE_COUNT = 2;

	/**
	 * UIHandler
	 * Filename:    DetailMBlogActivity.java 
	 * Package:     info.wegosoft.android.activity 
	 * Description: TODO(这里用一句话描述这个类的作用)
	 * Copyright:   Copyright (c) wegosoft.info 2011  
	 * @author:     李辉 
	 * email:       fzlihui@gmail.com
	 * @version:    1.0  
	 * Create at:   2011-6-17 下午09:20:15
	 */
	private class UIHandler extends Handler{
		
		public void handleMessage(Message msg) {

			// 此处可以更新主线程UI
			switch (msg.what) {
				case UPDATE_FACE:
					
					 if(faceBitmap!=null)
						 userFace.setImageBitmap(faceBitmap);
					 
					 break;
					 
				case UPDATE_IMAGE:
					
					 if(microBlogImageBitmap!=null)
						 mblogImage.setImageBitmap(microBlogImageBitmap);	
					 
					 break;
					 
				case UPDATE_COUNT:
					
					 tweet_redirect.setText(repostNum);
					 
					 tweet_comment.setText(commentNum);
					 
					 break;
					 
				default:
					break;
			}	
					
		}
		
	}
	
	/**
	 * 载入图片信息的进程
	 */
	private class UpdateImageThread extends Thread{

		private void initInfo() throws IOException{
			InputStream faceImageUrlStream = null;
			
			InputStream microBlogImageUrlStream = null;
			
			FileInputStream in = null;
			
			FileOutputStream out = null;
			
			// 头像,先判断本地是否有缓存，没有再下载头像
			File faceFile = new File(Environment.getExternalStorageDirectory()
					+ getResources().getString(R.string.user_face_dir_path)
					+ addCacheFlag + "/" + mBlog.getName() + ".jpeg");

			// 本地头像缓存存在
			if (faceFile.exists()) {

				in = new FileInputStream(faceFile);

				faceBitmap = BitmapFactory.decodeStream(in);

			// 本地缓存中不存在这个头像再下载并缓存到本地
			} else {

				// 有可能腾讯微博头像是默认的，此时mBlog.getHead()为空，就用默认的face
				if (mBlog.getHead() != null && !mBlog.getHead().trim().equals("")) {

					URL faceImageUrl = new URL(mBlog.getHead());

					faceImageUrlStream = faceImageUrl.openStream();

					faceBitmap = BitmapFactory.decodeStream(faceImageUrlStream);

					File dir = new File(Environment.getExternalStorageDirectory()
							+ getResources().getString(R.string.user_face_dir_path)
							+ addCacheFlag);
					
					if(!dir.exists())
						dir.mkdirs();
					
					if (faceFile.createNewFile()) {

						out = new FileOutputStream(faceFile);

						faceBitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);

					}

					// 以用户id缓存头像
					// out = context.openFileOutput(
					// context.getResources().getString(
					// R.string.face_cache_prefix) + addCacheFlag
					// + mBlog.getName() + ".jpeg",
					// Context.MODE_PRIVATE);

				}

			}
			
			handler.sendEmptyMessage(UPDATE_FACE);
			
			MBlog sourceMBlog = mBlog.getSourceMBlog();
			
			MBlog targetMBlog = null;
			
			//如果有原微博，则图片只可能在原微博。否则只可能在本微博
			if(sourceMBlog!=null && sourceMBlog.getBmiddle_pic() != null && !sourceMBlog.getBmiddle_pic().trim().equals(""))
				targetMBlog = sourceMBlog;
			else {
				targetMBlog = mBlog;
			}
			
			// 状态包含的图片,先判断本地是否有缓存，没有再下载
			if (targetMBlog.getBmiddle_pic() != null && !targetMBlog.getBmiddle_pic().trim().equals("")) {
				
				File picFile = new File(Environment.getExternalStorageDirectory()
						+ getResources().getString(
								R.string.mblog_images_dir_path) + addCacheFlag
						+ "/" + BMIDDLE_IMAGES_CACHE_DIR + "/" + targetMBlog.getId() + ".jpeg");

				// 本地存在图片缓存
				if (picFile.exists()) {

					in = new FileInputStream(picFile);

					microBlogImageBitmap = BitmapFactory.decodeStream(in);

				// 本地不存在图片缓存
				} else {

					// 本地不存在缓存，下载并缓存到本地
					URL microBlogImageUrl = new URL(targetMBlog.getBmiddle_pic());

					microBlogImageUrlStream = microBlogImageUrl.openStream();

					microBlogImageBitmap = BitmapFactory
							.decodeStream(microBlogImageUrlStream);

					File dir = new File(Environment.getExternalStorageDirectory()
							+ getResources().getString(
									R.string.mblog_images_dir_path) + addCacheFlag
							+ "/" + BMIDDLE_IMAGES_CACHE_DIR);
					
					if(!dir.exists())
						dir.mkdirs();
					
					if (picFile.createNewFile()) {

						out = new FileOutputStream(picFile);

						microBlogImageBitmap.compress(Bitmap.CompressFormat.JPEG,
								100, out);

					}
				}

				handler.sendEmptyMessage(UPDATE_IMAGE);
			}
			
			
		}
		
		@Override
		public void run() {
			
			try {
				initInfo();
			} catch (IOException e) {
				e.printStackTrace();
			}
			
		}
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {

		if (keyCode == KeyEvent.KEYCODE_BACK) {
		
			Intent intent = new Intent();
			
			intent.setClass(DetailMBlogActivity.this, MBlogListActivity.class);
			
			this.finish();
			
			startActivity(intent);
		}

		return super.onKeyDown(keyCode, event);
	}
}
